import { Node, mergeAttributes } from "@tiptap/core";

export interface PageBreakOptions {
  HTMLAttributes: Record<string, any>;
}

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    pageBreak: {
      /**
       * 插入分页符
       */
      setPageBreak: () => ReturnType;
    };
  }
}

/**
 * PageBreak 扩展
 * 用于在文档中插入分页符
 */
export const PageBreak = Node.create<PageBreakOptions>({
  name: "pageBreak",

  // 节点优先级（数字越大优先级越高）
  priority: 1000,

  // 是否可以作为默认内容
  addOptions() {
    return {
      HTMLAttributes: {
        class: "page-break",
      },
    };
  },

  // 定义节点组
  group: "block",

  // 定义是否可以选择
  selectable: true,

  // 定义是否可以拖动
  draggable: true,

  // 定义节点的内容规范（空内容，原子节点）
  content: "",

  // 定义节点可以包含在哪些节点中
  parseHTML() {
    return [
      {
        tag: 'div[data-type="page-break"]',
        getAttrs: (node) => {
          const el = node as HTMLElement;
          return {
            type: el.getAttribute("data-page-type") || "default",
          };
        },
      },
      {
        tag: "hr.page-break",
        getAttrs: (node) => {
          const el = node as HTMLElement;
          return {
            type: el.getAttribute("data-page-type") || "default",
          };
        },
      },
      // 支持 Word 导出后再次导入
      {
        tag: "p",
        getAttrs: (node) => {
          const el = node as HTMLElement;
          if (
            el.classList.contains("page-break") ||
            el.textContent?.trim() === "\f"
          ) {
            return { type: "default" };
          }
          return false;
        },
      },
    ];
  },

  // 定义节点如何渲染为 HTML
  renderHTML({ HTMLAttributes }) {
    return [
      "div",
      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
        "data-type": "page-break",
        "data-page-type": HTMLAttributes.type || "default",
      }),
    ];
  },

  // 添加命令
  addCommands() {
    return {
      setPageBreak:
        () =>
        ({ commands }) => {
          return commands.insertContent({
            type: this.name,
          });
        },
    };
  },

  // 添加键盘快捷键
  addKeyboardShortcuts() {
    return {
      // Ctrl+Enter 插入分页符（类似 Word）
      "Mod-Enter": () => {
        return this.editor.commands.setPageBreak();
      },
      // Shift+Enter 在某些场景下也可以
      "Shift-Mod-Enter": () => {
        return this.editor.commands.setPageBreak();
      },
    };
  },
});
